<?php

/**
 * 后台Controller
 */
namespace Common\Controller;
use Common\Controller\AppframeController;
use Think\Cache\Driver\Redis;

class AdminbaseController extends AppframeController {
	
	public function __construct() {
		$admintpl_path=C("SP_ADMIN_TMPL_PATH").C("SP_ADMIN_DEFAULT_THEME")."/";
		C("TMPL_ACTION_SUCCESS",$admintpl_path.C("SP_ADMIN_TMPL_ACTION_SUCCESS"));
		C("TMPL_ACTION_ERROR",$admintpl_path.C("SP_ADMIN_TMPL_ACTION_ERROR"));
		parent::__construct();
		$time=time();
		$this->assign("js_debug",APP_DEBUG?"?v=$time":"");
		
		//获取站点配置信息
		$siteConf = D('Options')->where("option_name='site_options'")->getField('option_value');
		$siteConfAry = json_decode($siteConf,true);
		
		L('ADMIN_CENTER',$siteConfAry['site_name']);
		
	}

    function _initialize(){
       parent::_initialize();
       $this->load_app_admin_menu_lang();
    	if(isset($_SESSION[APP_NAME]['ADMIN_ID'])){
    		$users_obj= M("Users");
    		$id=$_SESSION[APP_NAME]['ADMIN_ID'];
    		$user=$users_obj->where("id=$id")->find();
    		if(!$this->check_access($id)){
    			$this->error("您没有访问权限！");
    			exit();
    		}
    		$this->assign("admin",$user);
    	}else{
    		//$this->error("您还没有登录！",U("admin/public/login"));
    		if(IS_AJAX){
    			$this->error("您还没有登录！",U("admin/public/login"));
    		}else{
    			header("Location:".U("admin/public/login"));
    			exit();
    		}
    		
    	}
    }
    
    /**
     * 初始化后台菜单
     */
    public function initMenu() {
        $Menu = F("Menu");
        if (!$Menu) {
            $Menu=D("Common/Menu")->menu_cache();
        }
        return $Menu;
    }

    /**
     * 消息提示
     * @param type $message
     * @param type $jumpUrl
     * @param type $ajax 
     */
    public function success($message = '', $jumpUrl = '', $ajax = false) {
        parent::success($message, $jumpUrl, $ajax);
    }

    /**
     * 模板显示
     * @param type $templateFile 指定要调用的模板文件
     * @param type $charset 输出编码
     * @param type $contentType 输出类型
     * @param string $content 输出内容
     * 此方法作用在于实现后台模板直接存放在各自项目目录下。例如Admin项目的后台模板，直接存放在Admin/Tpl/目录下
     */
    public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
        parent::display($this->parseTemplate($templateFile), $charset, $contentType);
    }
    
    /**
     * 获取输出页面内容
     * 调用内置的模板引擎fetch方法，
     * @access protected
     * @param string $templateFile 指定要调用的模板文件
     * 默认为空 由系统自动定位模板文件
     * @param string $content 模板输出内容
     * @param string $prefix 模板缓存前缀*
     * @return string
     */
    public function fetch($templateFile='',$content='',$prefix=''){
        $templateFile = empty($content)?$this->parseTemplate($templateFile):'';
		return parent::fetch($templateFile,$content,$prefix);
    }
    
    /**
     * 自动定位模板文件
     * @access protected
     * @param string $template 模板文件规则
     * @return string
     */
    public function parseTemplate($template='') {
    	$tmpl_path=C("SP_ADMIN_TMPL_PATH");
    	define("SP_TMPL_PATH", $tmpl_path);
		// 获取当前主题名称
		$theme      =    C('SP_ADMIN_DEFAULT_THEME');
		
		if(is_file($template)) {
			// 获取当前主题的模版路径
			define('THEME_PATH',   $tmpl_path.$theme."/");
			return $template;
		}
		$depr       =   C('TMPL_FILE_DEPR');
		$template   =   str_replace(':', $depr, $template);
		
		// 获取当前模块
		$module   =  MODULE_NAME."/";
		if(strpos($template,'@')){ // 跨模块调用模版文件
			list($module,$template)  =   explode('@',$template);
		}
		// 获取当前主题的模版路径
		define('THEME_PATH',   $tmpl_path.$theme."/");
		
		// 分析模板文件规则
		if('' == $template) {
			// 如果模板文件名为空 按照默认规则定位
			$template = CONTROLLER_NAME . $depr . ACTION_NAME;
		}elseif(false === strpos($template, '/')){
			$template = CONTROLLER_NAME . $depr . $template;
		}
		
		C("TMPL_PARSE_STRING.__TMPL__",__ROOT__."/".THEME_PATH);
		
		C('SP_VIEW_PATH',$tmpl_path);
		C('DEFAULT_THEME',$theme);
		define("SP_CURRENT_THEME", $theme);
		
		$file = sp_add_template_file_suffix(THEME_PATH.$module.$template);
		$file= str_replace("//",'/',$file);
		if(!file_exists_case($file)) E(L('_TEMPLATE_NOT_EXIST_').':'.$file);
		return $file;
    }

    /**
     *  排序 排序字段为listorders数组 POST 排序字段为：listorder
     */
    protected function _listorders($model) {
        if (!is_object($model)) {
            return false;
        }
        $pk = $model->getPk(); //获取主键名称
        $ids = $_POST['listorders'];
        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $model->where(array($pk => $key))->save($data);
        }
        return true;
    }

    /**
     * 后台分页
     * 
     */
    protected function page($total_size = 1, $page_size = 0, $current_page = 1, $listRows = 6, $pageParam = '', $pageLink = '', $static = FALSE) {
        if ($page_size == 0) {
            $page_size = C("PAGE_LISTROWS");
        }
        
        if (empty($pageParam)) {
            $pageParam = C("VAR_PAGE");
        }
        
        $Page = new \Page($total_size, $page_size, $current_page, $listRows, $pageParam, $pageLink, $static);
        $Page->SetPager('Admin', '{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}<span>总记录{recordcount}</span>', array("listlong" => "9", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
        return $Page;
    }

    private function check_access($uid){
    	//如果用户角色是1，则无需判断
    	if($uid == 1){
    		return true;
    	}
    	
    	$rule=MODULE_NAME.CONTROLLER_NAME.ACTION_NAME;
    	$no_need_check_rules=array("AdminIndexindex","AdminMainindex");
    	
    	if( !in_array($rule,$no_need_check_rules) ){
    		return sp_auth_check($uid);
    	}else{
    		return true;
    	}
    }
    
    private function load_app_admin_menu_lang(){
    	if (C('LANG_SWITCH_ON',null,false)){
    		$admin_menu_lang_file=SPAPP.MODULE_NAME."/Lang/".LANG_SET."/admin_menu.php";
    		if(is_file($admin_menu_lang_file)){
    			$lang=include $admin_menu_lang_file;
    			L($lang);
    		}
    	}
    }
    
    /**
     * 通用分页列表数据集获取方法
     *
     *  可以通过url参数传递where条件,例如:  index.html?name=asdfasdfasdfddds
     *  可以通过url空值排序字段和方式,例如: index.html?_field=id&_order=asc
     *  可以通过url参数r指定每页数据条数,例如: index.html?r=5
     *
     * @param sting|Model  $model   模型名或模型实例
     * @param array        $where   where查询条件(优先级: $where>$_REQUEST>模型设定)
     * @param array|string $order   排序条件,传入null时使用sql默认排序或模型属性(优先级最高);
     *                              请求参数中如果指定了_order和_field则据此排序(优先级第二);
     *                              否则使用$order参数(如果$order参数,且模型也没有设定过order,则取主键降序);
     *
     * @param boolean      $field   单表模型用不到该参数,要用在多表join时为field()方法指定参数
     * @author 朱亚杰 <xcoolcc@gmail.com>
     *
     * @return array|false
     * 返回数据集
     */
    protected function lists ($model,$where=array(),$order='',$field=true){
        $options    =   array();
        //         $REQUEST    =   (array)I('request.');
        $REQUEST = $_REQUEST;
        if(is_string($model)){
            $model  =   M($model);
        }
    
        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);
    
        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        unset($REQUEST['_order'],$REQUEST['_field']);
    
        if(empty($where)){
            $where  =   array('status'=>array('gt',0));
        }
        if( !empty($where)){
            $options['where']   =   $where;
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();
    
        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = 20;
        }
         
        //         $page = new \Page($total, $listRows, $REQUEST);
        //         if($total>$listRows){
        // //             $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        //             $page->SetPager('Admin', '{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}', array("listlong" => "9", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
    
        //         }
        
        
        $page = $this->page($total, $listRows,1,$REQUEST['r']);
        $p =$page->show('Admin');
        $this->assign('page', $p? $p: '');
        $this->assign('total',$total);
        //         dump($page);
        $options['limit'] = $page->firstRow.','.$page->listRows;
    
        $model->setProperty('options',$options);
    
        return $model->field($field)->select();
    }
    
    /**
     * 删除数据,可批量
     * @param unknown $model
     * date:2016年11月22日
     * author: EK_熊
     */
    public function delete($model=''){
        $model = empty($model) ? $this->model : $model;
        $ids = I('ids');
        $pk = $model->getPk();
        $map[$pk] = array('in',$ids);
        $ret = $model->where($map)->delete();
        if (!$ret) $this->error('操作失败,网络异常！');
        $this->success('操作成功！');
    }
    
    /**
     * 修改单条记录状态
     * @param unknown $model
     * @param array $val
     * date:2016年11月22日
     * author: EK_熊
     */
    public function setStatus($model=''){
        $model = empty($model) ? $this->model : $model;
        $id = I('id');
        $status = I('status');
        $pk = $model->getPk();
        
        $ret = $model->where([$pk=>$id])->save(['status'=>$status,'updated_time'=>CURRENT_TIME]);
        if (!$ret) $this->error('操作失败,网络异常！');
        $this->success('操作成功！');
    }
    
    /**
     * 编辑
     * 
     * date:2016年11月22日
     * author: EK_熊
     */
    public function edit(){
        $id = I('id');
        $pk = $this->model->getPk();
        if (IS_POST){
            $post = I('post');
            $post['updated_time'] =CURRENT_TIME;
            $where[$pk] = $id;
            $ret = $this->model->where($where)->save($post);
            if (!$ret) $this->error('操作失败！');
            if (method_exists($this,'add_after')) $this->edit_after();
            $this->success('操作成功！');
        }
        $info = $this->model->where([$pk=>$id])->find();
        $this->assign('status',$this->status);
        $this->assign('info',$info);
        $this->display();
    }
    
    /**
     * 新增
     * 
     * date:2016年11月22日
     * author: EK_熊
     */
    public function add(){
        if (IS_POST) {
            $post = I('post');
            $post['created_time'] = $post['updated_time'] =CURRENT_TIME;
            $ret = $this->model->add($post);
            if (!$ret) $this->error('添加失败！');
            if (method_exists($this,'add_after')) $this->add_after();
            $this->success('添加成功！');
        }
    
        $this->assign('status',$this->status);
        $this->display();
    }
    
    /**
     * 编辑，redis版本，数据使用list方式保存
     * @param unknown $keyfield
     * date:2018年1月19日
     * author: EK_熊
     */
    public function edit_redis($keyfield){
        $id = I('id');
        $pk = $this->model->getPk();
        if (IS_POST){
            $redis = new Redis();
            $post = I('post');
            $post['update_time'] =CURRENT_TIME;
            $where[$pk] = $id;
            $oldkey = $this->model->where($where)->getField($keyfield);
            $ret = $this->model->where($where)->save($post);
            if (!$ret) $this->error('操作失败！');
             
            $redis->lRem($this->redis_key,$oldkey,0);
            $redis->lPush($this->redis_key,$post[$keyfield]);
             
            $this->success('操作成功！');
        }
        $info = $this->model->where([$pk=>$id])->find();
        $this->assign('status',$this->status);
        $this->assign('info',$info);
        $this->display();        
    }
    
    public function add_redis($field,$field_name){
        if (IS_POST) {
            $redis = new Redis();
            $post = I('post');
            $post['update_time'] =CURRENT_TIME;
            $post['create_time'] =CURRENT_TIME;
             
            $exist = $this->model->where(["$field"=>$post["$field"]])->find();
            if ($exist) $this->error("该{$field_name}已经存在");
             
            $ret = $this->model->add($post);
            if (!$ret) $this->error('添加失败！');
             
            $ret_redis = $redis->lPush($this->redis_key,$post["$field"]);
             
            $this->success('添加成功！');
        }
        
        $this->display();
    }
    
}